package com.javaweb.controller;

import com.javaweb.model.User;
import jakarta.validation.constraints.NotBlank;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/11/20 11:22
 */
@Controller
public class SystemController {

    @GetMapping({"/", "/index"})
    public String index() {
        return "login" ;
    }

    @GetMapping("backend/index")
    public String backIndex() {
        return "backend/index" ;
    }

    @GetMapping("articles/list")
    public String articleList() {
        return "backend/articles/list" ;
    }

    @GetMapping("articles/add")
    public String addArticle() {
        return "backend/articles/add" ;
    }

    @PostMapping("/sys/login")
    public String login(@RequestParam @NotBlank String username,
                        @RequestParam @NotBlank String password,
                        Model model) {

        if ( ! "123456".equals(password) ) {
            model.addAttribute("msg", "用户名或密码错误");
            return "error";
        }

        model.addAttribute("msg", "登录成功");
        model.addAttribute("user", username) ;
        return "welcome" ;



    }

    @PostMapping("/sys/login/json")
    @ResponseBody
    public ResponseEntity<String> login(@RequestParam @NotBlank String username,
                                @RequestParam @NotBlank String password) {

        if ( ! "123456".equals(password) ) {

//            return "error";
        }

//        model.addAttribute("msg", "登录成功");
//        model.addAttribute("user", username) ;
        return null ;
    }

    @GetMapping("/show-thy")
    public String showThy(Model model) {
        // 准备数据，将数据放置在model, 供视图使用
        model.addAttribute("message",
                "hello thymeleaf") ;
        model.addAttribute("user",
                                User.builder().name("zhangsan")
                                .isAdmin(false).build()) ;

        List<User> items = List.of(
                User.builder().name("zhangsan")
                        .isAdmin(false).build(),
                User.builder().name("lisi")
                        .isAdmin(false).build(),
                User.builder().name("wangwu")
                        .isAdmin(false).build()
        ) ;
        model.addAttribute("items", items) ;

        // 视图的逻辑名字
        return "show-thy" ;
    }

}
